package com.lej.core.webView

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.os.Build
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.FragmentActivity
import com.lej.core.base.app
import com.lej.core.base.statusHeight
import com.lej.core.common.PCacheInfo
import com.lej.core.dsl.dp
import com.lej.core.utils.extention.addUrlParams

/**模块中的js交互接口集合,每个模块有js交互的接口在各自的模块初始化时通过add添加到接口列表中*/
val jsInstances = ArrayList<(FragmentActivity) -> BaseJsInstance>()


fun WebView.handleLoadUrl(url: String?) {
    if (!url.isNullOrEmpty() && url.endsWith("mp4") && Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
        loadData(WebTools.getVideoHtmlBody(url), "text/html", "UTF-8")
    } else {
        loadUrl(url ?: "")
    }
}

/**
 * nftType 是否为订购
 */
internal fun String.addParams() = addUrlParams(
    "token" to (PCacheInfo.userToken()),
    "timestamp" to System.currentTimeMillis(),
    "height" to statusHeight,
    "type_url" to "pn",
    "os" to "1",//1:Android系统
)

@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
internal fun WebView.initWebView(
    mIWeb: IWebPageView,
    activity: FragmentActivity
): MyWebChromeClient {
    settings.let {
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        it.setSupportZoom(true)
        it.builtInZoomControls = true
        it.displayZoomControls = false
        // 设置缓存模式
        it.cacheMode = WebSettings.LOAD_DEFAULT
        // setDefaultZoom  api19被弃用
        // 网页内容的宽度自适应屏幕
        it.loadWithOverviewMode = true
        it.useWideViewPort = true
        // 告诉WebView启用JavaScript执行。默认的是false。
        it.javaScriptEnabled = true
        //  页面加载好以后，再放开图片
        it.blockNetworkImage = false
        // 使用localStorage则必须打开
        it.domStorageEnabled = true
        // webView从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        it.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        /* 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用)*/
        it.textZoom = 100
    }
    scrollBarSize = 3.dp
    val mWebChromeClient = MyWebChromeClient(mIWeb)
    webChromeClient = mWebChromeClient
    // 与js交互
    addJSInstance(activity)
    webViewClient = MyWebViewClient(mIWeb)
    setOnLongClickListener { handleLongImage() }
    WebView.setWebContentsDebuggingEnabled(app.isDebug)

    return mWebChromeClient
}

/**添加js接口*/
private fun WebView.addJSInstance(activity: FragmentActivity) {
    val jsIns = MyJavascriptInterface(activity)
    addJavascriptInterface(jsIns, jsIns.getInterfaceName())
    jsInstances.forEach {
        val jsInstance = it(activity)
        addJavascriptInterface(jsInstance, jsInstance.getInterfaceName())
    }
}

/**
 * 长按图片事件处理
 */
private fun WebView.handleLongImage(): Boolean {
    val hitTestResult = hitTestResult
    // 如果是图片类型或者是带有图片链接的类型
    if (hitTestResult.type == WebView.HitTestResult.IMAGE_TYPE ||
        hitTestResult.type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE
    ) { // 弹出保存图片的对话框
        return true
    }
    return false
}

internal fun WebView?.onDestroy() {
    this?.let {
        (it.parent as? ViewGroup)?.removeView(it)
        it.removeAllViews()
        it.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        it.stopLoading()
        it.webChromeClient = null
        it.webViewClient = WebViewClient()
        it.destroy()
    }
}

/**
 * 判断网络是否连通
 */
fun Context.isNetworkConnected() = kotlin.runCatching {
    (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
        .activeNetworkInfo?.isConnected ?: false
}.getOrElse { false }